<template>
  <permission-check type="exam">
    <div class="unarranged-container">
      <div class="top-actions">
        <!-- 搜索表单 -->

        <el-form :inline="true" class="search-form">
          <el-form-item label="授权名称" class="el-form-item">
            <el-input v-model="searchForm.username" placeholder="请输入授权名称" clearable />
          </el-form-item>
          <el-form-item label="考生姓名">
            <el-input v-model="searchForm.candidateName" placeholder="请输入考生姓名" clearable />
          </el-form-item>
          <el-form-item label="证件号码" class="el-form-item">
            <el-input v-model="searchForm.idNumber" placeholder="请输入证件号码" clearable />
          </el-form-item>
          <el-form-item label="报考专业" class="el-form-item">
            <el-select v-model="searchForm.major" placeholder="请选择报考专业" clearable>
              <el-option v-for="item in majorData" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="报考等级" class="el-form-item">
            <el-select v-model="searchForm.level" placeholder="请选择报考等级" clearable>
              <el-option v-for="item in levelData" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item label="报考日期" class="el-form-item">
            <el-date-picker v-model="searchForm.applicationDate" type="date" placeholder="请选择报考日期" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="成绩状态" class="el-form-item">
            <el-select v-model="searchForm.scoreStatus" placeholder="请选择成绩状态" clearable>
              <el-option v-for="item in scoreStatusData" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch" class="Button">查询</el-button>
            <el-button @click="resetForm" class="Button">重置</el-button>
          </el-form-item>
          <el-button type="primary" :disabled="!tableData.length" @click="handleExport" class="Button"> 导出报表 </el-button>
        </el-form>

        <!-- <el-button type="primary" @click="copeLinke">
              成绩查询链接
            </el-button> -->
      </div>
      <!-- 表格 -->
      <el-table v-loading="loading" :data="tableData" border class="el-table">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="candidateName" label="考生姓名" width="100" />
        <el-table-column prop="candidateNamePinyin" label="姓名拼音" width="160" />
        <el-table-column prop="gender" label="性别" width="60" />
        <el-table-column prop="major" label="报考专业" width="100" />
        <el-table-column prop="level" label="报考等级" width="100" />
        <el-table-column prop="idType" label="证件类型" width="100" />
        <el-table-column prop="idNumber" label="证件号码" width="220" />
        <el-table-column prop="admissionTicketNumber" label="准考证号" width="220" />

        <el-table-column prop="scoreStatus" label="成绩状态" width="100" />
        <el-table-column prop="currentAddress" label="现居地址" width="180" />

        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <div class="text-center">
              <!-- <el-button type="primary" @click="copyInquireLink(scope.row)" :disabled="!scope.row.viewGradesLink">查看成绩</el-button> -->
              <el-button type="primary" @click="handleView(scope.row)">查看</el-button>
              <el-button type="primary" @click="handleEdit(scope.row)" v-if="mainStore.userInfo.role.roleType >= 90"> 修改成绩 </el-button>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[14, 28, 50, 100,200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>

      <!-- 查看弹窗 -->
      <el-dialog v-model="viewDialogVisible" title="考生信息" width="800px">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="考生姓名">{{ currentRow.candidateName }}</el-descriptions-item>
          <el-descriptions-item label="姓名拼音">{{ currentRow.candidateNamePinyin }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ currentRow.gender }}</el-descriptions-item>
          <el-descriptions-item label="民族">{{ currentRow.ethnicity }}</el-descriptions-item>
          <el-descriptions-item label="国籍">{{ currentRow.nationality }}</el-descriptions-item>
          <el-descriptions-item label="证件号码">{{ currentRow.idNumber }}</el-descriptions-item>
          <el-descriptions-item label="准考证号">{{ currentRow.admissionTicketNumber }}</el-descriptions-item>
          <el-descriptions-item label="报考专业">{{ currentRow.major }}</el-descriptions-item>
          <el-descriptions-item label="报考等级">{{ currentRow.level }}</el-descriptions-item>
          <el-descriptions-item label="报考日期">{{ currentRow.applicationDate }}</el-descriptions-item>
          <el-descriptions-item label="报名机构">{{ currentRow.institution }}</el-descriptions-item>
          <el-descriptions-item label="所在校区">{{ currentRow.campus }}</el-descriptions-item>
          <el-descriptions-item label="现居地址">{{ currentRow.currentAddress }}</el-descriptions-item>
          <el-descriptions-item label="家长电话">{{ currentRow.parentPhone }}</el-descriptions-item>
          <el-descriptions-item label="指导老师">{{ currentRow.instructor }}</el-descriptions-item>
          <el-descriptions-item label="指导老师电话">{{ currentRow.instructorPhone }}</el-descriptions-item>
          <el-descriptions-item label="成绩状态">{{ currentRow.scoreStatus }}</el-descriptions-item>
          <!-- <el-descriptions-item label="成绩分数">{{ currentRow.score || 0 }}</el-descriptions-item> -->
        </el-descriptions>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="viewDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 修改成绩弹窗 -->
      <el-dialog v-model="editDialogVisible" title="修改成绩" width="500px">
        <el-form ref="editFormRef" :model="editForm" label-width="100px" :rules="editRules">
          <el-form-item label="考生姓名">
            <span>{{ currentRow.candidateName }}</span>
          </el-form-item>
          <el-form-item label="姓名拼音">
            <span>{{ currentRow.candidateNamePinyin }}</span>
          </el-form-item>
          <el-form-item label="考生性别">
            <span>{{ currentRow.gender }}</span>
          </el-form-item>
          <el-form-item label="准考证号">
            <span>{{ currentRow.admissionTicketNumber }}</span>
          </el-form-item>
          <el-form-item label="证件号码">
            <span>{{ currentRow.idNumber }}</span>
          </el-form-item>
          <el-form-item label="报考专业">
            <span>{{ currentRow.major }}</span>
          </el-form-item>
          <el-form-item label="报考等级">
            <span>{{ currentRow.level }}</span>
          </el-form-item>
          <el-form-item label="成绩状态" prop="scoreStatus">
            <el-select v-model="editForm.scoreStatus" placeholder="请选择成绩状态" style="width: 220px">
              <el-option label="通过" value="通过" />
              <el-option label="未通过" value="未通过" />
              <el-option label="缺考" value="缺考" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="分数" prop="score">
            <el-input-number v-model="editForm.score" :min="0" :max="100" :precision="1" style="width: 220px" />
          </el-form-item> -->
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitScore">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </permission-check>
</template>

<script setup>
  import { ref, reactive, onMounted, watch, computed } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Plus, Document, Delete } from '@element-plus/icons-vue';
  import Http from '@/utils/http';
  import { areaOptions } from '@/utils/area-data';
  import OSS from 'ali-oss';
  import { imgUrls } from '@/utils/utils';
  import { getSubuser, getExamApplications } from '@/api/api';
  import { domain } from '@/utils/config';
  import { useMainStore } from '@/stores/useMain';
  const mainStore = useMainStore();

  const majorData = ref(['主持']);
  const levelData = ref(['1级', '2级', '3级', '4级', '5级', '6级', '7级', '8级', '9级', '10级']);
  const scoreStatusData = ref(['通过', '未通过', '缺考']);

  // 搜索表单数据
  const searchForm = reactive({
    username: '', // 授权名称
    candidateName: '', // 考生姓名
    idNumber: '', //证件号码
    major: '', // 专业
    level: '',
    applicationDate: '', // 报考日期
    scoreStatus: '', // 成绩状态
  });
  const user_id = ref('');
  // 表格数据
  const tableData = ref([]);
  // 添加 loading 变量
  const loading = ref(false);

  // 分页数据
  const currentPage = ref(1);
  const pageSize = ref(14);
  const total = ref(100);

  // 机构选项
  const institutionOptions = ref([]);

  // 考级申报选项
  const declarationOptions = ref([]);

  // 查看弹窗相关
  const viewDialogVisible = ref(false);
  const currentRow = ref({});

  // 修改成绩弹窗相关
  const editDialogVisible = ref(false);
  const editFormRef = ref(null);
  const editForm = reactive({
    scoreStatus: '',
    score: 0,
  });

  // 表单验证规则
  const editRules = {
    scoreStatus: [{ required: true, message: '请选择成绩状态', trigger: 'change' }],
    score: [{ required: true, message: '请输入分数', trigger: 'blur' }],
  };

  // 生命周期钩子
  onMounted(() => {
    getInstitutions();
  });
  // 获取机构列表
  const getInstitutions = async () => {
    try {
      const data = await getSubuser();
      institutionOptions.value = data;

      // 如果只有一条数据，自动选中该 userId
      if (institutionOptions.value.length === 1) {
        user_id.value = institutionOptions.value[0].id;
      } else {
        getExamList();
      }
      // 移除这里的 getExamList 调用，因为 watch(user_id) 会处理它
    } catch (error) {
      console.error('获取机构列表失败：', error);
    }
  };

  // 获取考级申报列表
  const getDeclarationList = async () => {
    try {
      const data = await getExamApplications(user_id.value);
      declarationOptions.value = data.items || [];
    } catch (error) {
      ElMessage.error('获取考级申报列表失败');
      console.error('获取考级申报列表失败：', error);
    }
  };

  // 获取未安排考场的考生列表数据
  const getExamList = async () => {
    loading.value = true; // 开始加载
    try {
      const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
        userId: user_id.value,
        hasScore: true,
        ...searchForm,
      };

      const res = await Http.post({
        url: '/yp_admin/applyListLook',
        data: params,
      });
      tableData.value = res.data.list;
      total.value = res.data.pagination.total;
    } catch (error) {
      console.error('获取考生列表失败：', error);
      ElMessage.error('获取考生列表失败');
    } finally {
      loading.value = false; // 结束加载
    }
  };

  // 重置表单
  const resetForm = () => {
    searchForm.username = '';
    searchForm.candidateName = '';
    searchForm.idNumber = '';
    searchForm.major = '';
    searchForm.level = '';
    searchForm.applicationDate = '';
    searchForm.scoreStatus = '';
    // 只在有多个机构选项时才重置 user_id
    if (institutionOptions.value.length > 1) {
      user_id.value = '';
    }
    handleSearch();
  };

  // 搜索方法
  const handleSearch = () => {
    currentPage.value = 1;
    getExamList();
  };

  const handleSizeChange = (val) => {
    pageSize.value = val;
    getExamList();
  };

  const handleCurrentChange = (val) => {
    currentPage.value = val;
    getExamList();
  };

  // 监听机构选择变化
  watch(user_id, (newVal) => {
    if (newVal) {
      // 只在 user_id 有值时才获取数据
      getDeclarationList();
      handleSearch();
    }
  });

  // 查看详情
  const handleView = (row) => {
    currentRow.value = row;
    viewDialogVisible.value = true;
  };

  // 修改成绩
  const handleEdit = (row) => {
    currentRow.value = row;
    editForm.scoreStatus = row.scoreStatus || '通过';
    editForm.score = row.score || 0;
    editDialogVisible.value = true;
  };

  // 提交成绩
  const submitScore = async () => {
    if (!editFormRef.value) return;

    await editFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const params = {
            examRegistrationId: currentRow.value.id,
            scoreStatus: editForm.scoreStatus,
            score: editForm.score,
          };

          await Http.post({
            url: '/yp_admin/markScore',
            data: params,
          });

          ElMessage.success('修改成绩成功');
          editDialogVisible.value = false;
          getExamList(); // 刷新列表
        } catch (error) {
          console.error('修改成绩失败：', error);
          ElMessage.error('修改成绩失败');
        }
      }
    });
  };

  // 添加导出方法
  const handleExport = async () => {
    const res = await Http.post({
      url: '/yp_admin/exportGradeForm',
      data: {
        userId: user_id.value || undefined,
        hasScore: true,
        ...searchForm,
      },
    });

    if (res.data.url) {
      const downloadUrl = imgUrls(res.data.url);
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = res.data.fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      ElMessage.success('导出成功');
    } else {
      ElMessage.warning('未找到可下载的文件');
    }

    // window.open(imgUrls(res.data.url), '_blank');
  };

  const copyInquireLink = (row) => {
    if (!row.viewGradesLink) {
      ElMessage.warning('暂无成绩查询链接');
      return;
    }
    navigator.clipboard.writeText(row.viewGradesLink);
    ElMessage.success('成绩查询链接已复制到剪贴板');
  };

  const copeLinke = () => {
    navigator.clipboard.writeText(domain + '/exam/#/pages/inquire/inquire');
    ElMessage.success('成绩查询链接已复制到剪贴板');
  };
</script>

<style scoped lang="scss">
  .el-form--inline .el-form-item {
    margin-right: 10px !important;
    :deep(.el-form-item__content) {
      width: 180px !important;
      .el-input {
        height: 100%;
      }
    }
  }
  .el-select,
  .el-input {
    width: 180px;
  }
  .unarranged-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    padding: 20px;
    overflow: hidden; // 防止溢出
    display: flex;
    flex-direction: column;

    .top-actions {
      display: flex;
      margin-bottom: 20px;
    }

    :deep(.el-input__wrapper) {
      height: 40px;
      line-height: 40px;
    }

    :deep(.el-form-item__label) {
      height: 40px;
      line-height: 40px;
      padding-right: 12px;
      white-space: nowrap;
    }
    .search-form {
      margin-bottom: 0;
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 10px;
      :deep(.el-form-item) {
        margin-bottom: 0;
        margin-right: 10px;

        &:last-child {
          margin-right: 0;
        }
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .el-table {
    flex: 1;
    width: 100%;
    overflow: scroll;
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  .el-descriptions {
    padding: 20px;
  }
</style>
